// lib/src/services/translation_service.dart

import 'dart:convert';
import 'dart:async';
import 'package:http/http.dart' as http;

class TranslationService {
  // 简单的内存缓存: { "英文原文_目标语言代码": "翻译后文本" }
  final Map<String, String> _translationCache = {};
  bool _enableApiTranslation = false; // 开关：是否启用真实API翻译
  final String _deepSeekApiKey; // API密钥将通过构造函数传入

  // DeepSeek API 端点
  static const String _deepSeekEndpoint =
      'https://api.deepseek.com/chat/completions';

  TranslationService({
    bool enableApiTranslation = false,
    String deepSeekApiKey = "",
  }) : _deepSeekApiKey = deepSeekApiKey {
    _enableApiTranslation = enableApiTranslation;
    if (_enableApiTranslation) {
      if (_deepSeekApiKey.isEmpty) {
        print(
          "Warning: AI translation service is enabled but DeepSeek API key is not provided. Translation will fail.",
        ); // 英文警告
      } else {
        print("AI translation service enabled (using DeepSeek API)."); // 英文日志
      }
    } else {
      print("AI translation service is in mock mode."); // 英文日志
    }
  }

  /// 内部方法：使用 DeepSeek API 进行翻译
  Future<String> _translateWithDeepSeekAPI(
    String text, // 期望是英文原文
    String targetLang, { // 目标语言代码
    Duration timeoutDuration = const Duration(seconds: 15),
  }) async {
    // 确保源文本确实是英文，或者API能够处理源语言自动检测（如果支持）
    // DeepSeek 的 prompt 最好明确源语言，但这里我们假设 text 总是英文
    final prompt =
        'Translate the following English phrase into $targetLang and return only the translated phrase: "$text"';

    try {
      final response = await http
          .post(
            Uri.parse(_deepSeekEndpoint),
            headers: {
              'Authorization': 'Bearer $_deepSeekApiKey',
              'Content-Type': 'application/json; charset=utf-8', // 确保UTF-8
            },
            body: jsonEncode({
              'model': 'deepseek-chat',
              'messages': [
                {
                  'role': 'system',
                  'content':
                      'You are a precise translator. Provide only the direct translation of the given phrase in the target language. No explanations, no formatting. UTF-8 only.',
                },
                {'role': 'user', 'content': prompt},
              ],
              'stream': false,
            }),
          )
          .timeout(timeoutDuration);

      if (response.statusCode == 200) {
        final responseBody = utf8.decode(response.bodyBytes); // 确保UTF-8解码
        final decoded = jsonDecode(responseBody);

        if (decoded['choices'] is List &&
            decoded['choices'].isNotEmpty &&
            decoded['choices'][0]['message']?['content'] != null) {
          String translatedText =
              decoded['choices'][0]['message']['content'].trim();

          // 移除可能的首尾引号
          if ((translatedText.startsWith('"') &&
                  translatedText.endsWith('"')) ||
              (translatedText.startsWith('「') &&
                  translatedText.endsWith('」'))) {
            if (translatedText.length > 1) {
              translatedText = translatedText.substring(
                1,
                translatedText.length - 1,
              );
            }
          }
          return translatedText;
        } else {
          print(
            '[DeepSeek API Error] Unexpected response structure for "$text" to $targetLang:\n$responseBody',
          );
          return text; // 返回原文作为后备
        }
      } else {
        final errorBody = utf8.decode(response.bodyBytes);
        print(
          '[DeepSeek API Error ${response.statusCode}] for "$text" to $targetLang:\n$errorBody',
        );
        return text; // 返回原文作为后备
      }
    } on TimeoutException catch (e) {
      print(
        '[DeepSeek API Timeout] for "$text" to $targetLang after ${timeoutDuration.inSeconds}s.\n$e',
      );
      return text; // 返回原文作为后备
    } catch (e) {
      print(
        '[DeepSeek API Exception] Failed to translate "$text" to $targetLang.\n$e',
      );
      return text; // 返回原文作为后备
    }
  }

  /// 翻译文本。
  /// [englishText]：要翻译的英文文本 (作为翻译的键)。
  /// [targetLanguageCode]：目标语言代码 (例如 "ar", "zh", "es")。
  /// [useCache]：是否使用缓存。
  Future<String> translate(
    String englishText,
    String targetLanguageCode, {
    bool useCache = true,
  }) async {
    // 如果目标语言是英文，或文本为空，则直接返回原文
    if (targetLanguageCode.toLowerCase() == 'en' ||
        englishText.trim().isEmpty) {
      return englishText;
    }

    final cacheKey = "${englishText}_$targetLanguageCode";
    // 检查缓存
    if (useCache && _translationCache.containsKey(cacheKey)) {
      return _translationCache[cacheKey]!;
    }

    // 如果未启用API翻译或API密钥为空，则使用模拟翻译
    if (!_enableApiTranslation || _deepSeekApiKey.isEmpty) {
      String mockTranslation =
          "$englishText [mock translated to $targetLanguageCode]";
      if (useCache) {
        _translationCache[cacheKey] = mockTranslation;
      }
      return mockTranslation;
    }

    // 调用DeepSeek API进行翻译
    String translatedText = await _translateWithDeepSeekAPI(
      englishText,
      targetLanguageCode,
    );

    if (useCache) {
      _translationCache[cacheKey] = translatedText;
    }
    return translatedText;
  }
}
